import browser from 'webextension-polyfill';

function onMessage(message, sender, sendResponse) {
    try {
        if (message.attachRecorderRequest) {
            sendResponse(false);
            return true;
        } else if (message.frameLocation) {
            // todo
        } else if (message.setFrameNumberForTab) {
            const { indicatorIndex } = message;
            // todo
        } else if (message?.action === 'activateServiceWorker') {
            // console.log('收到消息，唤醒休眠的service_worker', sender);
            sendResponse({
                action: 'activateServiceWorker',
                msg: '唤醒休眠的service_worker',
            });
        } else {
            console.log(message, sender, sendResponse, 'service_worker 收到消息');
        }
        return true;
    } catch (error) {
        console.error('Error processing message:', error);
    }
}

// 收到消息，唤醒service_worker
chrome.runtime.onMessage.addListener(onMessage);

// 点击action
chrome.action.onClicked.addListener(async (tab) => {
    // 打开popup.html
    const wnd = await chrome.windows.create({
        type: 'popup',
        url: chrome.runtime.getURL('popup.html'),
    });
    await browser.tabs.sendMessage(tab.id, { attachRecorder: true });
});
